var editor;
var hintTables = new Array();
$(function () {
    $("#fw-toolbar-search").off('click').on('click', function () {
        // $("#form-sql-search").parent(".fw-search-collapse").slideToggle();
        // sqlFormatter();
    });

    $("#fw-toolbar-refresh").off('click').on('click', function () {
        $.table.refresh("jquery-datatables");
    });

    editor = CodeMirror.fromTextArea(document.getElementById("sql-code-textarea"), {
        lineNumbers: true,     // 显示行数
        indentUnit: 4,         // 缩进单位为4
        styleActiveLine: true, // 当前行背景高亮
        matchBrackets: true,   // 括号匹配
        mode: "text/x-mariadb",    // 设置编辑器语言为JavaScript
        lineWrapping: true,    // 自动换行
        theme: 'default',      // 使用default模版
        fontSize: 14,
        scrollbarStyle: 'overlay', //属性，字符串类型，有两个值，overlay和simple两种滚动条样式，
        // hintOptions: {tables:{'table1':{array:[{text:'column1',displayText:'column1',type:' [int2] database.table1'},{text:'column2',displayText:'column1[vachar2]',type:'  database.table1'}],type:'table'},'function1':{array:[],type:'  function'}}}
    });
    // 添加示例代码
    var exampleCode = ``;
    editor.setOption("extraKeys", {
        // Tab键换成4个空格
        Tab: function (cm) {
            var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
            cm.replaceSelection(spaces);
        },
        // F11键切换全屏
        "F11": function (cm) {
            cm.setOption("fullScreen", !cm.getOption("fullScreen"));
        },
        // Esc键退出全屏
        "Esc": function (cm) {
            if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
        }
    });
    // 将示例代码添加到编辑器中
    editor.setValue(exampleCode);
    // 监听代码变化事件
    editor.on("change", function (cm) {
        var code = cm.getValue();
        $("#sql-code").val(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode(code)))));
    });
    // 监听代码选中事件
    editor.on("cursorActivity", function (cm) {
        var code = cm.getSelection();
        if (code != '') {
            $.common.clearSelection();
            $("#sql-code").val(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode(code)))));
            $("#fw-toolbar-execute").html(" 运行已选择");
            $("#fw-toolbar-explain").html(" 解释已选择");
        } else {
            $("#sql-code").val(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode(cm.getValue())))));
            $("#fw-toolbar-execute").html(" 运行");
            $("#fw-toolbar-explain").html(" 解释");
        }
    });
    editor.on("keyup", function (cm, event) {
        // 监听 Ctrl + V 黏贴等
        /*if ((event.ctrlKey && event.keyCode === 86) || (event.ctrlKey && event.keyCode === 88) || event.keyCode === 8 || event.keyCode === 46 || event.keyCode === "Delete") {
            console.log("=======",Array.from(extractTableNames(cm.getValue())))
            hintTables = Array.from(extractTableNames(cm.getValue()));
            getHintTables();
        }*/
        // 监听 Ctrl + R
        /*if (event.ctrlKey && event.keyCode == 82) {
            execute(sql_oper_type.EXECUTE);
        }*/

        if (!cm.state.completionActive//所有的字母和'$','{','.'在键按下之后都将触发自动完成
            && !event.ctrlKey && ((event.keyCode >= 65 && event.keyCode <= 90 && event.keyCode != 86)
                || event.keyCode == 52 || event.keyCode == 219
                || event.keyCode == 190)) {
            CodeMirror.commands.autocomplete(cm, null, {
                completeSingle: false
            });
        }
    });
    getHintTables();

    editor.focus();

    $.contextMenu({
        selector: ".CodeMirror",
        trigger: 'right',
        autoHide: false,
        items: {
            "execute": {
                name: "运行",
                callback: function (key, opt) {
                    execute(sql_oper_type.EXECUTE);
                }
            },
            "step1": "---------",
            "cut": {
                name: "剪切",
                callback: function (key, opt) {
                    // var cut_value = $.base64.decode($.base64.decode($.base64.decode(decodeURIComponent($("#sql-code").val()))));
                    jianshezhong();
                }
            },
            "copy": {
                name: "复制",
                callback: function (key, opt) {
                    var copy_value = $.base64.decode($.base64.decode($.base64.decode(decodeURIComponent($("#sql-code").val()))));
                    $.common.copyToClipboard(copy_value);
                }
            },
            "step2": "---------",
            "select_all": {
                name: "全选",
                callback: function (key, opt) {
                    jianshezhong();
                }
            },
        }
    });

});


/**
 * 代码提示--提取sql包含的表名
 * @param sqlStatements
 * @returns {*[]}
 */
function extractTableNames(sqlStatements) {
    // 分割 SQL 语句
    const sqlQueries = sqlStatements.split(';');
    // 用于存储提取出的表名
    const tableNames = [];
    // 正则表达式，用于提取表名
    const regex = /(?:from|join)\s+(\w+)/gi;
    // 对每个 SQL 语句进行处理
    sqlQueries.forEach((query) => {
        let match;
        while ((match = regex.exec(query)) !== null) {
            tableNames.push(match[1]);
        }
    });
    return tableNames;
}
// 代码提示--回调函数
function hintCompletionTables(completion) {
    /*if(!(completion.text in hintTables)) hintTables.push(completion.text);
    getHintTables();*/
}
// 代码提示--获取sql编写表、字段提示信息
function getHintTables() {
    if (!verifyRequireConnectVal()) {
        return;
    }
    var connectId = $("input[name='connectId']").val();
    var databaseName = $("input[name='databaseName']").val();
    $.ajax({
        type: "POST",
        url: ctx + "osfw/dbadminer/database/table/hint",
        data: "connectId=" + connectId + "&database=" + databaseName + "&tableNames=" + hintTables,
        dataType: "json",
        async: true,
        success: function (res) {
            if (res.code == web_status.SUCCESS) {
                if (res.data != null) {
                    editor.setOption("hintOptions", {tables: res.data});
                }
            }
        },
        error: function (xhr, status, error) {
            var errorMessage = "请求失败，请稍后再试。";
            if (xhr.status === 0) {
                errorMessage = "网络连接失败，请检查网络设置。";
            } else if (xhr.status === 404) {
                errorMessage = "请求的资源不存在。";
            } else if (xhr.status === 500) {
                var responseText = JSON.parse(xhr.responseText);
                errorMessage = responseText.msg;
            } else if (error === "timeout") {
                errorMessage = "请求超时，请稍后再试。";
            }
            // 显示错误提示给用户
            $.modal.alertError(errorMessage);
        }
    });
}

/**
 * 执行、解释、停止
 * @param _tag
 */
function execute(_tag) {
    if (!verifyRequireConnectVal()) {
        $.modal.msgWarning("需要先指定一下数据库哦");
        return;
    }
    var _clz = _tag == sql_oper_type.EXPLAIN ? "result-explain" : "result-data";
    var _title = _tag == sql_oper_type.EXPLAIN ? "解释" : "结果";
    if (_tag == sql_oper_type.EXECUTE) {
        //执行
        $.resultTab.init(_clz);
        $.dataTable.executeTab(_clz, _title);

    } else if (_tag == sql_oper_type.EXPORT) {
        //导出
        $.modal.confirm("确认要导出当前查询结果吗？", function () {
            $.dataTable.exportData();
        });

    } else {
        //解释、停止
        jianshezhong();
    }
}


/**
 * 验证执行操作是否已指定数据库
 * @returns {boolean}
 */
function verifyRequireConnectVal() {
    var connectId = $("input[name='connectId']").val();
    var databaseName = $("input[name='databaseName']").val();
    if (connectId == -1 || connectId == '' || connectId == undefined || connectId == null
        || databaseName == '--' || databaseName == '' || databaseName == undefined || databaseName == null) {
        return false;
    }
    return true;
}


// divScroll("result-data");
var $connect_selected = $('#connect-select');
var $database_selected = $('#database-select');
$(function () {
    // var topWindow = $(window.parent.document);
    // $('.fw-content', topWindow).css("box-shadow", "0px 0px 5px 1px rgba(0,0,0,0.2)");

    $connect_selected.on('change', function() {
        // $(this).find('option').eq(this.selectedIndex).text();
        var connect_selected_val = $(this).val();
        $("input[name='connectId']").val(connect_selected_val);
        var iframe_data_id = $(".moxia_iframe",window.parent.document).not(".am-hide").data("id");
        var $menu_tab_a = $(".fw-menu[data-id="+iframe_data_id+"]",window.parent.document).find("a");
        $menu_tab_a.removeClass("connect-group-0 connect-group-1 connect-group-2 connect-group-3 connect-group-4");
        $menu_tab_a.addClass("connect-group-"+$('#connect-select option[value="'+connect_selected_val+'"]').data("connect_group"));
        var title = (connect_selected_val == undefined || connect_selected_val == '--') ? '无标题' : $(this).find('option').eq(this.selectedIndex).text();
        title += " - 查询";
        $menu_tab_a.prop("title", title);
        var $menu_tab_span = $(".fw-menu[data-id="+iframe_data_id+"]",window.parent.document).find("span");
        $menu_tab_span.text(" " + title);
        $('.fw-main').removeClass("connect-group-0 connect-group-1 connect-group-2 connect-group-3 connect-group-4");
        $('.fw-main').addClass("connect-group-"+$('#connect-select option[value="'+connect_selected_val+'"]').data("connect_group"));
        renewalDatabaseList(connect_selected_val);
    });
    $database_selected.on('change', function() {
        // $(this).find('option').eq(this.selectedIndex).text();
        var database_selected_val = $(this).val();
        $("input[name='databaseName']").val(database_selected_val);
        if(database_selected_val != '') {
            var connect_selected_label = $('#connect-select').find('option').filter(function(index) {
                return this.selected;
            }).text();
            var title = (database_selected_val == undefined || database_selected_val == '--') ? '无标题' : database_selected_val + " ("+connect_selected_label+")";
            title += " - 查询";
            var iframe_data_id = $(".moxia_iframe",window.parent.document).not(".am-hide").data("id");
            var $menu_tab_a = $(".fw-menu[data-id="+iframe_data_id+"]",window.parent.document).find("a");
            $menu_tab_a.prop("title", title);
            var $menu_tab_span = $(".fw-menu[data-id="+iframe_data_id+"]",window.parent.document).find("span");
            $menu_tab_span.text(" " + title);
        }
        getHintTables();
    });
});

function renewalDatabaseList(connect_id) {
    $database_selected.html("");
    $database_selected.append('<option value=""></option>');
    $.ajax({
        type: "get",
        async: true,
        url: ctx + "osfw/dbadminer/database/list/" + connect_id,
        success: function (res) {
            if (res.code == web_status.SUCCESS) {
                $.each(res.data, function(i, database_name) {
                    $database_selected.append('<option icon="am-icon-database" value="' + database_name +'">' + database_name + '</option>');
                });
            } else {
                $.modal.msgWarning("未匹配到可用数据库..");
            }
        },
        error: function(xhr, status, error) {
            var errorMessage = "请求失败，请稍后再试。";
            if (xhr.status === 0) {
                errorMessage = "网络连接失败，请检查网络设置。";
            } else if (xhr.status === 404) {
                errorMessage = "请求的资源不存在。";
            } else if (xhr.status === 500) {
                var responseText = JSON.parse(xhr.responseText);
                errorMessage = responseText.msg;
            } else if (error === "timeout") {
                errorMessage = "请求超时，请稍后再试。";
            }
            // 显示错误提示给用户
            $.modal.alertError(errorMessage);
        }
    });
}

